# -*- coding: utf-8 -*-
import os
from pyltp import Segmentor, Postagger, NamedEntityRecognizer

class Singleton(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_the_instance'):
            cls._the_instance = object.__new__(cls, *args, **kwargs)
        return cls._the_instance
class time_address_extract_model(Singleton):
    # print('load ltp model start...')

    pwd = os.getcwd()
    project_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + ".")

    LTP_DATA_DIR = 'D:\ltp_data\ltp_data'  # ltp模型目录的路径
    cws_model_path = os.path.join(LTP_DATA_DIR, 'cws.model')
    pos_model_path = os.path.join(LTP_DATA_DIR, 'pos.model')  # 词性标注模型路径，模型名称为`pos.model`
    ner_model_path = os.path.join(LTP_DATA_DIR, 'ner.model')  # 命名实体识别模型路径，模型名称为`ner.model`

    # print('path' + cws_model_path)

    segmentor = Segmentor()  # 初始化实例
    segmentor.load(cws_model_path)  # 加载模型

    postagger = Postagger() # 初始化实例
    postagger.load(pos_model_path)  # 加载模型

    recognizer = NamedEntityRecognizer() # 初始化实例
    recognizer.load(ner_model_path)  # 加载模型


    def get_model(self):
        return self.segmentor, self.postagger, self.recognizer

    def free_model(self):
        self.segmentor.release()  # 释放模型
        self.postagger.release()
        self.recognizer.release()


def get_address_prediction(words, netags):
    # model = time_address_extract_model()
    # segmentor, postagger, recognizer = segmentor, postagger, recognizer
    result_address = []
    result_group = []
    for i in range(0, len(netags)):
        # print(words[i] + ': ' + netags[i])
        # 地名标签为 ns
        if 's' in netags[i]:
            result_address.append(words[i])
        # 公司标签为 ni
        if 'B-Ni' in netags[i]:
            result_group.append(words[i])
        if 'I-Ni' in netags[i]:
            result_group[-1]+=words[i]
        if 'E-Ni' in netags[i]:
            result_group[-1]+=words[i]
    result = result_address+result_group
    if len(result) < 1:
        result = []
    # print(result)
    return list(set(result))


def get_address(words, netags):
    # print("start get_address...")
    result = "Exception"
    try:
        result = get_address_prediction(words, netags)
    except Exception as ex:
        print(ex)

    # print("Output is " + result)
    return result

# 获取文本中的时间
def get_time(words, postags):
    # segmentor, postagger, recognizer = segmentor, postagger, recognizer
    # 开始分词及词性标注
    # words = segmentor.segment(text)
    # postags = postagger.postag(words)

    time_list = []

    i = 0
    for tag, word in zip(postags, words):
        if tag == 'nt':
            j = i
            while postags[j] == 'nt' or words[j] in ['至', '到']:
                j += 1
            time_list.append(''.join(words[i:j]))
        i += 1

    # 去重子字符串的情形
    remove_list = []
    for i in time_list:
        for j in time_list:
            if i != j and i in j:
                remove_list.append(i)

    text_time_list = []
    for item in time_list:
        if item not in remove_list:
            text_time_list.append(item)

    # print(text_time_lst)
    return list(set(text_time_list))


def get_elements(segmentor, postagger, recognizer, text):
    words = segmentor.segment(text)  # 分词
    postags = postagger.postag(words)  # 词性标注
    netags = recognizer.recognize(words, postags)  # 命名实体识别
    address_list = get_address(words, netags)
    time_list = get_time(words, postags)
    return address_list, time_list

if __name__ == '__main__':
    model = time_address_extract_model()
    segmentor, postagger, recognizer = model.get_model()
    text = "事发现场。视频截图8月4日上午，江苏省南京市消防救援支队官方微博通报，4日5时39分，南京化学工业园区方水路90号-98南京协和助剂有限公司一厂房发生火灾，南京市消防救援支队指挥中心已调集救援力量到场处置。7时04分，现场明火扑灭。现场无人员伤亡。天眼查信息显示，南京协和助剂有限公司于2004年12月15日在南京市工商行政管理局化学工业园区分局登记成立。公司经营范围包括FWR复合稳定剂和XH系列改质剂的生产、销售；新材料、新技术的技术转让、服务、开发和咨询。澎湃新闻注意到，前述公司曾于2016年7月因未按规定提交年度报告信息被南京市工商行政管理局化学工业园区分局列入企业经营异常名录，后于同年8月移出。"
    address_list, time_list = get_elements(segmentor, postagger, recognizer, text)
    print(address_list, time_list)
    model.free_model()